//
//  ViewController.m
//  EcShop
//
//  Created by soft on 2017/10/24.
//  Copyright © 2017年 soft. All rights reserved.
//

#import "ViewController.h"
#import "HTTPMananger.h"
#import "Banner.h"
#import "Classic.h"
#import "Utility.h"
#import "PYSearch.h"
#import "SDCycleScrollView.h"
#import "Searchask.h"
#import "ProductDetails.h"
#import "IndexTableViewCell.h"
#import "SearchDetailsViewController.h"
#import "DataSorting.h"
#import "productDetailsViewController.h"
#import "ClassifyViewController.h"


@interface ViewController () <UISearchControllerDelegate,UITextFieldDelegate,PYSearchViewControllerDelegate,SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) NSArray *searchRList;
@property (nonatomic,strong) NSArray<Banner *> *banners;
@property (nonatomic,strong)   NSArray *classics;
@property (nonatomic,strong) NSArray<ProductDetails *> *productList;
@property (nonatomic,strong)NSMutableArray *hotSeaches;//推荐搜索
@property (nonatomic,strong) UIScrollView *demoContainerView;
@property (nonatomic,strong) UITableView *taleV;
@property (nonatomic,strong)UISegmentedControl *segmentControl;
@end

@implementation ViewController
-(NSMutableArray *)hotSeaches{
    if (!_hotSeaches) {
        _hotSeaches = [NSMutableArray new];
        return _hotSeaches;
    }
    return _hotSeaches;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
    SHOW_HUD;

   
    [self getData];

    [self navV];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)tableV{
    self.taleV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+self.view.bounds.size.height*0.2, self.view.bounds.size.width, self.demoContainerView.contentSize.height-64-self.view.bounds.size.height*0.2)];
   // self.taleV.center =CGPointMake(self.view.bounds.size.width*0.5, self.view.bounds.size.height*0.6);
    //self.taleV.backgroundColor = [UIColor redColor];
    [self.demoContainerView addSubview:self.taleV];
    self.taleV.delegate = self;
    self.taleV.dataSource = self;
    

    self.segmentControl = [[UISegmentedControl alloc]initWithItems:@[@"新品上架",@"热门商品"]];
    //tintColor改变UISegmentedControl默认的选中颜色
    self.segmentControl.tintColor = [UIColor redColor];
    [self.segmentControl setFrame:CGRectMake(100, 160, 160,30 )];
    
    //self.segmentControl.segmentedControlStyle = UISegmentedControlStylePlain;
    //self.segmentControl.segmentedControlStyle = UISegmentedControlStyleBordered;
   // self.segmentControl.segmentedControlStyle = UISegmentedControlStyleBar;
    self.segmentControl.segmentedControlStyle = UISegmentedControlStyleBezeled;

    //apportionsSegmentWidthsByContent = YES,UISegmentedControl会根据其内容而改变前提是    [self.segmentControlView setTranslatesAutoresizingMaskIntoConstraints:NO];
   // [self.segmentControl addTarget:self action:@selector(segmentControlViewOnClick:) forControlEvents:UIControlEventValueChanged];
    self.segmentControl.apportionsSegmentWidthsByContent = NO;
    //momentary ＝ YES , we don't keep showing selected state after tracking ends. default is NO,点击其中一个Item 和uibutton的点击事件一样，显示一下selected state之后恢复普通状态
    self.segmentControl.momentary = YES;
    [self.demoContainerView addSubview: self.segmentControl];
    
}
//获取网络数据
-(void)getData{
    //搜索推荐
    [[HTTPMananger sharedManager]searchRecommend:^(NSDictionary *object, NSError *error) {
                if (error) {
        
                    return;
                }
        NSArray *a=object[@"searchRecommend"];
        for (int i=0; i<a.count; i++) {
            [self.hotSeaches addObject:a[i][@"key"]];
        }
                NSLog(@"%@",object);
            }];
    
    
    //主页轮播
        [[HTTPMananger sharedManager]home:^(NSDictionary *object, NSError *error) {
            if (error) {
                return ;
            }
            NSLog(@"%@",object);
            self.banners = [Banner mj_objectArrayWithKeyValuesArray:object[@"home_banner"]];
           // self.classics = [Classic mj_objectArrayWithKeyValuesArray:object[@"home_classic"]];
            NSLog(@"%@---%@",self.banners,self.classics);
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //回调或者说是通知主线程刷新，
//               [self ScrollIma];
//                   [self tableV];
//
//            });
            
        }];
    DataSorting * sek = [DataSorting new];
    sek.orderby = @"nil";
    sek.page = @"nil";
    sek.offset = @"nil";
    NSDictionary *dict = [self getObjectData:sek];
    [[HTTPMananger sharedManager]newProduct:^(NSDictionary *object, NSError *error) {
        if (error) {
            
            return;
        }
        HIDE_HUD;
        [Utility showMsg:@"接口访问成功！"];
        NSArray<ProductDetails *> *pl = [NSArray new];
        pl = [ProductDetails mj_objectArrayWithKeyValuesArray:object[@"productlist"]];
        self.productList = [ProductDetails mj_objectArrayWithKeyValuesArray:object[@"productlist"]];
        NSLog(@"%@",object);
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [self ScrollIma];
            [self tableV];
            
        });
    } product:dict];

    
}
//nav
-(void)navV{
    
    
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Left" style:UIBarButtonItemStylePlain target:self action:@selector(test1)];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"分类" style:UIBarButtonItemStylePlain target:self action:@selector(test2)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    
    UITextField *nav = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.view.frame.size.width*0.6, self.navigationController.view.frame.size.height)];
    nav.center = CGPointMake(self.navigationController.view.frame.size.width*0.5, self.navigationController.view.frame.size.height*0.5);
    nav.delegate = self;
    nav.placeholder = @"七彩虹";
   // nav.userInteractionEnabled = NO;
    self.navigationItem.titleView = nav;
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:50/255.0 green:138/255.0 blue:233/255.0 alpha:1.0];
    
}
//导航栏按钮
-(void)test1{
    
}
//导航栏按钮
-(void)test2{
   // ClassifyViewController *prv = [[ClassifyViewController alloc]init];
   // prv.prodtD = self.productList[indexPath.row];
          ClassifyViewController *prv = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"fenlei"];
    [self.navigationController pushViewController:prv animated:YES];
}
//搜索
-(void)textFieldDidBeginEditing:(UITextField*)textField

{
    
    [textField resignFirstResponder];
    [self searchView];
   // NSLog(@"111111");
    
}
//搜索
-(void)searchView{
    // 1. Create an Array of popular search
    // 2. Create a search view controller
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:self.hotSeaches  searchBarPlaceholder:NSLocalizedString(@"七彩虹", @" ") didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        // Called when search begain.
        // eg：Push to a temp view controller
//        [searchViewController.navigationController pushViewController:[[SearchDetailsViewController alloc] init] animated:NO];
        SearchDetailsViewController *vcc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"searchboard"];
        vcc.title = searchText;
//        SearchDetailsViewController * Controller = [self.storyboard instantiateViewControllerWithIdentifier:@"searchboard"];
 [searchViewController.navigationController pushViewController: vcc animated:YES];
        

        
    }];
    // 3. Set style for popular search and search history
        int a = (arc4random()%5)+1;
        int b = (arc4random()%4)+1;
        searchViewController.hotSearchStyle = a;
        searchViewController.searchHistoryStyle = b;
    // 4. Set delegate
    searchViewController.delegate = self;
    // 5. Present a navigation controller
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:nav animated:YES completion:nil];
}


//轮播
-(void)ScrollIma{
   // self.demoContainerView = [[UIScrollView alloc] initWithFrame:self.view.frame];
     self.demoContainerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64,self.view.bounds.size.width, self.view.bounds.size.height-64)];
    self.demoContainerView.contentSize = CGSizeMake(self.view.frame.size.width, 1200);
    [self.view addSubview:self.demoContainerView];
    // 情景二：采用网络图片实现
    NSMutableArray *imagesURLStrings = [NSMutableArray new];
    for (int i = 0; i<self.banners.count; i++) {
        [imagesURLStrings addObject:self.banners[i].imaLink];
    }
    // 网络加载 --- 创建自定义图片的pageControlDot的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,self.view.bounds.size.width, self.view.bounds.size.height*0.2) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
    cycleScrollView.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
    cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    cycleScrollView.autoScrollTimeInterval = 2;//轮播时间
    [self.demoContainerView addSubview:cycleScrollView];
    
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    
 //   [self.navigationController pushViewController:[NSClassFromString(@"DemoVCWithXib") new] animated:YES];
}



 
 // 滚动到第几张图回调
// - (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index
// {
// NSLog(@">>>>>> 滚动到第%ld张图", (long)index);
// }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//#pragma mark - PYSearchViewControllerDelegate
//- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
//{
//    if (searchText.length) {
//        // Simulate a send request to get a search suggestions
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            NSMutableArray *searchSuggestionsM = [NSMutableArray array];
//            for (int i = 0; i < arc4random_uniform(5) + 10; i++) {
//                NSString *searchSuggestion = [NSString stringWithFormat:@"Search suggestion %d", i];
//                [searchSuggestionsM addObject:searchSuggestion];
//            }
//            // Refresh and display the search suggustions
//            searchViewController.searchSuggestions = searchSuggestionsM;
//        });
//    }
//}
//对象转字典
- (NSDictionary*)getObjectData:(id)obj {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
    
    for(int i = 0;i < propsCount; i++) {
        
        objc_property_t prop = props[i];
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value == nil) {
            
            value = [NSNull null];
        } else {
            value = [self getObjectInternal:value];
        }
        [dic setObject:value forKey:propName];
    }
    
    return dic;
}

- (id)getObjectInternal:(id)obj {
    
    if([obj isKindOfClass:[NSString class]]
       ||
       [obj isKindOfClass:[NSNumber class]]
       ||
       [obj isKindOfClass:[NSNull class]]) {
        
        return obj;
        
    }
    if([obj isKindOfClass:[NSArray class]]) {
        
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        
        for(int i = 0; i < objarr.count; i++) {
            
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
        }
        return arr;
    }
    if([obj isKindOfClass:[NSDictionary class]]) {
        
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        
        for(NSString *key in objdic.allKeys) {
            
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }
        return dic;
    }
    return [self getObjectData:obj];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.productList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    // 从重用队列里查找可重用的cell
    IndexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    // 判断如果没有可以重用的cell，创建
    if (!cell) {
        cell = [[IndexTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.nameLbl.text =  self.productList[indexPath.row].name;
    
    cell.priceLbl.text = [NSString stringWithFormat:@"￥:%@",self.productList[indexPath.row].price];
    
    cell.descriptionsLbl.text = self.productList[indexPath.row].descriptions[@"desc"];
    NSArray *imas =self.productList[indexPath.row].pics;
    [self download:cell ImageWithUrl:imas[0][@"url"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    productDetailsViewController *prv = [[productDetailsViewController alloc]init];
    prv.prodtD = self.productList[indexPath.row];
    [self.navigationController pushViewController:prv animated:YES];
}

//异步线程加载网络下载图片 ——> 回到主线程更新UI
-(void)download:(IndexTableViewCell *)cell ImageWithUrl:(NSString *)imageDownloadURLStr{
    //以便在block中使用
    __block UIImage *image = [[UIImage alloc] init];
    //图片下载链接
    NSString *url = [NSString stringWithFormat:@"https://cdnme.azurewebsites.net%@",imageDownloadURLStr];
    NSURL *imageDownloadURL = [NSURL URLWithString:url];
    
    //将图片下载在异步线程进行
    //创建异步线程执行队列
    dispatch_queue_t asynchronousQueue = dispatch_queue_create("imageDownloadQueue", NULL);
    //创建异步线程
    dispatch_async(asynchronousQueue, ^{
        //网络下载图片  NSData格式
        NSError *error;
        NSData *imageData = [NSData dataWithContentsOfURL:imageDownloadURL options:NSDataReadingMappedIfSafe error:&error];
        if (imageData) {
            image = [UIImage imageWithData:imageData];
        }
        //回到主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            // [_imageView setImage:image];
            cell.ima.image = image;
            cell.ima1.image = image;
            cell.ima2.image = image;
        });
    });
}




@end
